package sk.demo.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import sk.demo.jpa.entity.Message;
import sk.demo.jpa.repository.MessageRepository;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * @author sk.z
 */
@Service
public class MessageService {

    @Autowired
    private MessageRepository messageRepository;

    public List<Message> getByUser(String userId){
        List<Message> list = messageRepository.findByUserId(userId);
        return list;
    }

    public Message getById(Long id){
        Optional<Message> message = messageRepository.findById(id);
        System.out.println(message.toString());
        return message.orElse(null);
    }

    public List<Message> getByUserGtId(String userId, Long id){
        List<Message> list = messageRepository.getByUserGtId(userId, id);
        return list;
    }

    public List<Message> getByContent(String segment){
        List<Message> list = messageRepository.getByContent(segment,PageRequest.of(0,10));
        return list;
    }

    public long saveRandom(){
        Message message = new Message();
        Random random = new Random();
        int r = random.nextInt(99999999);
        message.setTitle("te-"+r);
        message.setContent("con-"+r);
        message.setUserId(String.valueOf(r));
        message.setCreateTime(new Date());
        message = messageRepository.save(message);
        return message.getMesId();
    }

    public List<Message> page(int page, int size){
        Page<Message> all = messageRepository.findAll(PageRequest.of(page - 1, size, Sort.by("mesId").descending()));
        return all.getContent();
    }
}
